/*
 * @Description: 
 * @Author: paddies
 * @Date: 2024-06-03 02:18:58
 * @LastEditors: paddies
 * @LastEditTime: 2025-03-18 21:33:14
 * @FilePath: /shared_components/lib/uploadImage.dart
 */
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_components/build-common/buildCommon.dart';
import 'dart:convert';

import 'package:shared_components/init.dart';

uploadImage(
    {required XFile originalImage,
    String imageType = '',
    Function? onOcrContent,
    Function? onSuccess}) async {
  print("进行上传操作");

  String path = originalImage.path;
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  FormData formData = FormData.fromMap({
    "file": await MultipartFile.fromFile(path, filename: name),
    "ocrType": imageType
  });
  print("上传地址===" + '${sharedManager.uploadURL}');
  print("ocrType:" + imageType);
  print("token:" + sharedManager.token);

  // String token = GlobalPrefs.getToken() ?? "";
  String token = sharedManager.token;

  try {
    var dio = new Dio();
    dio.options = BaseOptions(
      // baseUrl: RequestConfig.baseUrl,
      connectTimeout: sharedManager.connectTimeout,
      sendTimeout: sharedManager.sendTimeout,
      receiveTimeout: sharedManager.receiveTimeout,
      headers: {
        "Authorization": "Bearer $token",
      },
      // contentType: Headers.jsonContentType,
      responseType: ResponseType.plain,
    );

    EasyLoading.show(status: '上传中...', maskType: EasyLoadingMaskType.black);

    var response = await dio.post('${sharedManager.uploadURL}', data: formData);
    EasyLoading.dismiss();
    Map<String, dynamic> responseData = jsonDecode(response.toString());
    int res_code = responseData["code"];
    String msg = showText(responseData["msg"]);
    print("上传响应====");
    print(responseData);
    if (res_code == 200) {
      var res_data = responseData["data"];
      var ocrContent = res_data["ocrContent"];
      print("上传返回值");
      print(res_data);
      print(ocrContent);
      var imgUrl = res_data["url"];
      print("上传成功");
      print(responseData);
      print(imgUrl);
      if (onSuccess != null) {
        onSuccess(imgUrl);
      }
      if (onOcrContent != null) {
        onOcrContent(ocrContent);
      }
      // doUpdateUserAvatar(imgUrl).then((res) {
      //   print("更新头像成功");
      //   GlobalPrefs.saveValue("userImgUrl", imgUrl);
      //   if (onSuccess != null) {
      //     onSuccess();
      //   }
      // });
    } else {
      EasyLoading.showError(msg);
    }
  } catch (e) {
    EasyLoading.dismiss();
    EasyLoading.showError("上传失败");
    // loadingHide();
    print("上传失败");
    print(e);
    ;
  }
}
